import { axiosInstance } from './axiosInstance';
import { API_PATHS } from './apiConfig';
import toastService from './toastService';
import type { User, ApiResponse } from '../types/anime';

// 用户登录
export const login = async (username: string, password: string): Promise<{ success: boolean; user?: User; error?: string }> => {
  try {
    const response = await axiosInstance.post<ApiResponse<string>>(
      API_PATHS.USER.LOGIN,
      { username, password }
    );
    
    if (response.data.code !== 200) {
      toastService.error(response.data.msg);
      return { success: false, error: response.data.msg };
    }
    
    // 获取token
    const token = response.data.data;
    
    if (!token) {
      return { success: false, error: '登录失败，未获取到令牌' };
    }
    
    // 保存令牌到本地存储
    localStorage.setItem('authorization', token);
    
    // 创建cookie，设置7天过期时间
    const expiryDate = new Date();
    expiryDate.setDate(expiryDate.getDate() + 7);
    
    // 设置cookie，包含过期时间和必要属性
    document.cookie = `authorization=${token}; expires=${expiryDate.toUTCString()}; path=/; SameSite=Lax`;
    
    // 获取用户信息
    const userInfo = await getCurrentUser();
    
    // 设置登录状态标志
    if (userInfo) {
      localStorage.setItem('isLoggedIn', 'true');
    }
    
    return { success: true, user: userInfo || undefined };
  } catch (error) {
    console.error('登录失败:', error);
    // 登录失败时，不调用getCurrentUser接口，直接返回错误信息
    if (error instanceof Error && 'response' in error && 
        (error as any).response) {
      const responseData = (error as any).response.data || {};
      return { success: false, error: responseData.msg || '用户名或密码错误' };
    }
    return { success: false, error: '登录失败，请稍后再试' };
  }
}

// 用户注册
export const register = async (username: string, password: string, email?: string): Promise<{ success: boolean; error?: string }> => {
  try {
    const response = await axiosInstance.post<ApiResponse<null>>(
      API_PATHS.USER.REGISTER,
      { username, password, email }
    );
    
    if (response.data.code !== 200) {
      toastService.error(response.data.msg);
      return { success: false, error: response.data.msg };
    }
    
    return { success: true };
  } catch (error) {
    console.error('注册失败:', error);
    if (error instanceof Error && 'response' in error && (error as any).response) {
      const responseData = (error as any).response.data || {};
      return { success: false, error: responseData.msg || '用户名已存在或格式错误' };
    }
    return { success: false, error: '注册失败，请稍后再试' };
  }
}

// 获取当前登录用户
export const getCurrentUser = async (): Promise<User | null> => {
  try {
    // 首先从本地存储获取用户信息
    const token = localStorage.getItem('authorization') || getCookie('authorization');
    
    if (!token) {
      // 如果没有令牌，清除用户信息并返回null
      localStorage.removeItem('user');
      return null;
    }
    
    // 调用后端API验证用户并获取最新信息
    const response = await axiosInstance.get<ApiResponse<User>>(API_PATHS.USER.CURRENT);
    
    if (response.data.code !== 200) {
      toastService.error(response.data.msg);
      throw new Error(response.data.msg);
    }
    
    // 更新本地存储中的用户信息
    localStorage.setItem('user', JSON.stringify(response.data.data));
    
    return response.data.data;
  } catch (error) {
    console.error('获取当前用户失败:', error);
    // 如果验证失败，清除本地存储
    if (error instanceof Error && 'response' in error && (error as any).response && 
        ((error as any).response.status === 401 || (error as any).response.status === 403)) {
      localStorage.removeItem('user');
      localStorage.removeItem('authorization');
      document.cookie = 'authorization=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
      return null;
    }
    // 非验证错误时，返回本地存储的用户信息
    const userStr = localStorage.getItem('user');
    return userStr ? JSON.parse(userStr) : null;
  }
}

// 辅助函数：从cookie中获取值
const getCookie = (name: string): string | null => {
  const cookieValue = document.cookie
    .split('; ') 
    .find(row => row.startsWith(`${name}=`)) 
    ?.split('=')[1];
  return cookieValue ? decodeURIComponent(cookieValue) : null;
}

// 用户登出
export const logout = async (): Promise<void> => {
  try {
    // 调用后端API使令牌失效
    await axiosInstance.post<ApiResponse<null>>(API_PATHS.USER.LOGOUT);
  } catch (error) {
    console.error('登出时调用API失败:', error);
    // 即使API调用失败，也继续清除本地存储
  } finally {
    try {
      // 清除 localStorage 中的用户信息和令牌
      localStorage.removeItem('user');
      localStorage.removeItem('authorization');
      
      // 清除 cookie 中的令牌
      document.cookie = 'authorization=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
    } catch (error) {
      console.error('登出失败:', error);
    }
  }
}

// 验证用户是否已登录
export const isAuthenticated = (): boolean => {
  // 检查本地存储中是否存在用户信息和令牌
  const user = localStorage.getItem('user');
  const token = localStorage.getItem('authorization') || getCookie('authorization');
  return !!user && !!token;
}